package cn.sockstack.controller;

import cn.sockstack.entity.User;
import cn.sockstack.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class RegisterController {
    @Autowired
    private UserService userService;

    @GetMapping(value = "register")
    public String showRegister() {
        return "register";
    }

    @PostMapping(value = "register")
    public String doRegister(
            @RequestParam(value = "username") String username,
            @RequestParam(value = "password") String password,
            @RequestParam(value = "confirm_password") String confirm_password,
            Model model
    )
    {
        System.out.println(password);
        System.out.println(confirm_password);
        if (!password.equals(confirm_password)){
            model.addAttribute("error", "两次密码不一致");
            return "register";
        }
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        int i = userService.create(user);
        if (i < 1) {
            model.addAttribute("error", "创建用户失败");
            return "register";
        }

        return "redirect:/";
    }
}
